<script setup lang="ts">
import {
    defineProps,
    getCurrentInstance,
    onMounted,
    ref,
    watch,
    defineEmits,
    onUnmounted
} from 'vue'

const props = defineProps({
    keywords: {
        type: Array<string>,
        required: true,
        default: () => {
            return []
        }
    },
    keywordsColor: {
        type: String,
        required: false,
        default: '#FF0000'
    }
})

const emit = defineEmits(['keywordSelect'])

const onKeywordClickCallback = (keyword) => {
    emit('keywordSelect', keyword)
}

if (!window.callbacks) {
    window.callbacks = []
}

const instance = getCurrentInstance()
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const replaced = ref(true)

watch(props.keywords, () => {
    replaced.value = false
    handleKeywords()
})

const handleKeywords = () => {
    if (!replaced.value) {
        let newHtml = instance?.proxy.$el.innerHTML
        const innerText = instance?.proxy.$el.innerText
        props.keywords.forEach((keyword) => {
            if (innerText.indexOf(keyword) >= 0) {
                newHtml = newHtml.replace(
                    new RegExp(keyword, 'g'),
                    '<span onclick="onKeywordClick(this,\'' +
                        keyword +
                        '\')" style="cursor:pointer;color:' +
                        props.keywordsColor +
                        '">' +
                        keyword +
                        '</span>'
                )
            }
        })
        instance.proxy.$el.innerHTML = newHtml
        replaced.value = true
    }
}

onMounted(() => {
    if (window.callbacks.indexOf(onKeywordClickCallback) < 0) {
        window.callbacks.push(onKeywordClickCallback)
    }
    replaced.value = false
    handleKeywords()
})

window.onKeywordClick = (e, keyword) => {
    if (window.callbacks) {
        for (const index in window.callbacks) {
            window.callbacks[index](keyword)
        }
    }
}

onUnmounted(() => {
    if (window.callbacks) {
        const index = window.callbacks.indexOf(onKeywordClickCallback)
        if (index >= 0) {
            window.callbacks.splice(index, 1)
        }
    }
})
</script>

<template>
    <div style="width: 100%; height: 100%"><slot></slot></div>
</template>

<style scoped></style>
